from fastapi import APIRouter, Query
from datetime import datetime, timedelta
from typing import Optional, List
import random
from .websocket_router import generate_mock_data

router = APIRouter(prefix="/api", tags=["api"])

# Mock data for RPA tasks
bank_names = ["工商银行", "建设银行", "农业银行", "中国银行", "交通银行", "招商银行", "浦发银行", "民生银行", "兴业银行", "平安银行", "中原银行", "华润银行", "湖北银行", "广发银行", "东莞银行", "广州银行"]
status_options = ["成功", "失败", "运行中"]

@router.get("/tasks")
async def get_tasks(
    
    status: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None
):
    """
    Get RPA tasks with optional filters
    """
    # Use the same mock data generation function as WebSocket
    # This ensures we're using the same current data without accumulation
    data = generate_mock_data()
    tasks = data["bank_tasks"]
    
    # Apply filters if provided
    if status:
        tasks = [task for task in tasks if task["status"] == status]
    
    # Apply date filters if provided
    if start_date and end_date:
        try:
            start_datetime = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
            end_datetime = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
            
            # Filter tasks by date range
            filtered_tasks = []
            for task in tasks:
                task_start_time = datetime.strptime(task["start_time"], "%Y-%m-%d %H:%M:%S")
                if start_datetime <= task_start_time <= end_datetime:
                    filtered_tasks.append(task)
            
            tasks = filtered_tasks
        except ValueError as e:
            print(f"Date parsing error: {e}")
    
    return {
        "tasks": tasks,
        "filters": {
            "status": status,
            "start_date": start_date,
            "end_date": end_date
        }
    }

@router.get("/summary")
async def get_summary():
    """
    Get summary of RPA tasks
    """
    # Use the same mock data generation function as WebSocket
    # This ensures we're using the same current data without accumulation
    data = generate_mock_data()
    return data["summary"]

@router.get("/monthly-stats")
async def get_monthly_stats(
    month: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None
):
    """
    Get monthly statistics for RPA execution by bank
    """
    # If time range is provided, use that instead of month
    if start_date and end_date:
        try:
            start_datetime = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
            end_datetime = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
            
            # Use the date range for the stats title
            date_range = f"{start_date} to {end_date}"
            
            # Generate mock monthly statistics for the date range
            monthly_stats = generate_mock_stats_for_time_range(start_datetime, end_datetime)
            
            return {
                "date_range": date_range,
                "stats": monthly_stats
            }
        except ValueError as e:
            print(f"Date parsing error: {e}")
    
    # If no month or time range is provided, use current month
    if not month:
        current_date = datetime.now()
        month = current_date.strftime("%Y-%m")
    
    # Generate mock monthly statistics for each bank
    monthly_stats = generate_mock_stats_for_month(month)
    
    return {
        "month": month,
        "stats": monthly_stats
    }

def generate_mock_stats_for_month(month):
    """Generate mock statistics for a given month"""
    monthly_stats = []
    
    # Create a list of RPA names (more than the bank_names to test pagination)
    rpa_names = []
    for bank in bank_names:
        rpa_names.append(f"{bank}-对账RPA")
        rpa_names.append(f"{bank}-报表RPA")
        rpa_names.append(f"{bank}-清算RPA")
    
    # Generate stats for each RPA
    for rpa in rpa_names:
        # Generate random statistics for the RPA
        success_count = random.randint(80, 200)
        failed_count = random.randint(5, 30)
        total_count = success_count + failed_count
        success_rate = round((success_count / total_count) * 100, 2)
        
        monthly_stats.append({
            "rpa_name": rpa,
            "success_count": success_count,
            "failed_count": failed_count,
            "total_count": total_count,
            "success_rate": success_rate
        })
    
    return monthly_stats

def generate_mock_stats_for_time_range(start_datetime, end_datetime):
    """Generate mock statistics for a given time range"""
    monthly_stats = []
    
    # Create a list of RPA names (more than the bank_names to test pagination)
    rpa_names = []
    for bank in bank_names:
        rpa_names.append(f"{bank}-对账RPA")
        rpa_names.append(f"{bank}-报表RPA")
        rpa_names.append(f"{bank}-清算RPA")
    
    # Generate stats for each RPA
    for rpa in rpa_names:
        # Generate random statistics for the RPA based on time range length
        # More days = more executions
        days_diff = (end_datetime - start_datetime).days + 1
        base_executions = max(1, days_diff * 2)  # At least 2 executions per day
        
        success_count = random.randint(base_executions, base_executions * 3)
        failed_count = random.randint(0, base_executions)
        total_count = success_count + failed_count
        success_rate = round((success_count / total_count) * 100, 2) if total_count > 0 else 100.0
        
        monthly_stats.append({
            "rpa_name": rpa,
            "success_count": success_count,
            "failed_count": failed_count,
            "total_count": total_count,
            "success_rate": success_rate
        })
    
    return monthly_stats 